<?php

class Tree_Node
{
	var $_root;
	var $_children;

	function Tree_Node()
	{
		$this->_root = NULL;
		$this->_children = array();
	}

	function root()
	{
		return $this->_root;
	}

	function child($index)
	{
		if(array_key_exists($index, $this->_children))
			return $this->_children[$index];
		return NULL;
	}

	function &children()
	{
		return $this->_children;
	}

	function set_root($elem)
	{
		$this->_root = $elem;
	}

	function set_child($child, $index)
	{
		$this->_children[$index] = $child;
	}

	function set_children(&$children)
	{
		$this->_children = $children;
	}
}

class TreeM
{
	var $_root;

	function TreeM()
	{
		$this->_root = new Tree_Node();
	}

	function is_leaf()
	{
		!$this->has_children();
	}

	function root()
	{
		return $this->_root->root();
	}

	function &children()
	{
		return $this->_root->children();
	}

	function has_children()
	{
		$children =& $this->children();

		return !empty($children);
	}

	static function factory($elem, $children = array())
	{
		$tree = new TreeM();
		$tree->_root->set_root($elem);
		$tree->_root->set_children(&$children);
		return $tree;
	}

	function insert($sub_tree)
	{
		$children =& $this->_root->children();
		$children[] = $sub_tree;
	}

	function remove($index)
	{
		$children =& $this->children();
		if(array_key_exists($index, $children))
			unset($children[$index]);
	}
}
